package com.hongyi.utils;


import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: hongyi
 * @CreateTime: 2024-10-22
 */


public class HttpUtils1 {


    /**
     * 执行HTTP GET请求
     *
     * @param host   主机地址
     * @param path   请求路径
     * @param method 请求方法（对于GET请求，该参数实际上不会被使用）
     * @return HttpResponse对象，包含服务器响应的信息
     * @throws Exception 执行请求时可能抛出的异常
     */
    public static HttpResponse doGet(String host, String path, String method)
            throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpGet request = new HttpGet(buildUrl(host, path));
        return httpClient.execute(request);
    }


    /**
     * 执行HTTP POST请求，以表单形式提交数据
     *
     * @param host   目标服务器的主机地址
     * @param path   请求的路径
     * @param method 请求的方法（对于POST请求，该参数实际上不会被使用）
     * @param bodys  表单提交的数据
     * @return HttpResponse对象，包含服务器响应的信息
     * @throws Exception 执行请求时可能抛出的异常
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> bodys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpPost request = new HttpPost(buildUrl(host, path));

        // 定义固定的 headers，并设置 Content-Type 为 application/json
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }
        return httpClient.execute(request);
    }

    /**
     * 发送POST请求，并发送字符串作为请求体。
     *
     * @param host   目标服务器的主机地址
     * @param path   请求的路径
     * @param method 请求的方法（对于POST请求，该参数实际上不会被使用）
     * @param body   请求体内容，作为字符串传递
     * @return HttpResponse对象，包含服务器响应的信息
     * @throws Exception 执行请求时可能抛出的异常
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpPost request = new HttpPost(buildUrl(host, path));

        // 定义固定的 headers，并设置 Content-Type 为 application/json
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");


        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        return httpClient.execute(request);
    }

    /**
     * 发送POST请求，并发送字节数组作为请求体。
     *
     * @param host   目标服务器的主机地址
     * @param path   请求的路径
     * @param method 请求的方法（对于POST请求，该参数实际上不会被使用）
     * @param body   请求体内容，作为字节数组传递
     * @return HttpResponse对象，包含服务器响应的信息
     * @throws Exception 执行请求时可能抛出的异常
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpPost request = new HttpPost(buildUrl(host, path));

        // 定义固定的 headers，并设置 Content-Type 为 application/json
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");


        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        return httpClient.execute(request);
    }

    /**
     * 发送PUT请求，并发送字符串作为请求体。
     *
     * @param host   目标服务器的主机地址
     * @param path   请求的路径
     * @param method 请求的方法（对于PUT请求，该参数实际上不会被使用）
     * @param body   请求体内容，作为字符串传递
     * @return HttpResponse对象，包含服务器响应的信息
     * @throws Exception 执行请求时可能抛出的异常
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpPut request = new HttpPut(buildUrl(host, path));

        // 定义固定的 headers，并设置 Content-Type 为 application/json
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");


        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        return httpClient.execute(request);
    }


    /**
     * Put stream
     *
     * @param host
     * @param path
     * @param method
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,

                                     byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpPut request = new HttpPut(buildUrl(host, path));

        // 定义固定的 headers，并设置 Content-Type 为 application/json
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");


        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        return httpClient.execute(request);
    }

    /**
     * 执行HTTP DELETE请求。
     *
     * @param host   目标服务器的主机地址
     * @param path   请求的路径
     * @param method 请求的方法（对于DELETE请求，该参数实际上不会被使用）
     * @return HttpResponse对象，包含服务器响应的信息
     * @throws Exception 执行请求时可能抛出的异常
     */
    public static HttpResponse doDelete(String host, String path, String method)
            throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpDelete request = new HttpDelete(buildUrl(host, path));
        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        return sbUrl.toString();
    }


    /**
     * 包装客户端
     *
     * @param host 主机地址
     * @return HttpClient实例
     */
    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }
        return httpClient;
    }


    /**
     * @param httpClient
     */
    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                }

                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }


}
